package com.hn.controller;

import com.hn.Util.WebChatUtil;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * 微信开发者接入
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "wx")
public class WebChatController {

    // 开发者接入验证 确认请求来自微信服务器
    @RequestMapping(value = "mywebchat.html", method = RequestMethod.GET)
    public void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        String echostr = request.getParameter("echostr");//成为开发者验证
        //确认此次GET请求来自微信服务器，原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
        PrintWriter out = response.getWriter();
        if (WebChatUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.println("=======请求校验成功======" + echostr);
            out.print(echostr);
        }
        out.close();
    }

    public void post(HttpServletRequest request, HttpServletResponse response) throws Exception {

    }


    //==================================================================================================================
    //==================================================================================================================
    //==================================================================================================================

    //1.进入授权页面
    @ResponseBody
    @RequestMapping(value = "authlogin.html", method = RequestMethod.GET)
    public void authlogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String APPID = "wx170f015f023e71fa";
        //编码格式处理
        String path = "http://ssm.vipgz1.idcfengye.com/wx/redirectUrl.html";

        String encodePath = URLEncoder.encode(path, "UTF-8");

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID +
                "&redirect_uri=" + encodePath +//用户授权后的回调地址
                "&response_type=code" +
                "&scope=snsapi_userinfo" +//显授权
                "&state=wcd#wechat_redirect";

        //获取到了用户资源
        String user_reuslt = request.getParameter(EntityUtils.toString(new DefaultHttpClient().execute(new HttpPost(url)).getEntity(), "UTF-8"));

        //2.重定向(用户请求进来后，会弹出一个授权框，用户同意授权后就携带参数，跳转到这个重定向地址)
        response.sendRedirect(url);

    }

    //2.获取相关参数
    //回调地址（获取code）
    @ResponseBody
    @GetMapping("redirectUrl.html")
    public String redirectUrl(HttpServletRequest request) throws IOException {
        //获得code
        String code = request.getParameter("code");
        String state = request.getParameter("state");//获取状态（wcd）
        request.getParameter("APPID");//获取appid（wx170f015f023e71fa）

        //通过code获取access_token
        String APPID = "wx170f015f023e71fa";
        String appsecret = "9fd577a7292d2b66cf587f9d29fb81b7";
        //获取access_token的地址
        String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
                "&secret=" + appsecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        //把地址以post的方式发送出去
        DefaultHttpClient client = new DefaultHttpClient();//获取DefaultHttpClient请求
        //发送请求工具类
        HttpPost access_httpost = new HttpPost(access_token_url);
        HttpResponse response = client.execute(access_httpost);//使用HttpResponse接收client执行httpost的结果
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");//HttpEntity转为字符串类型
        //获取access_token
        JSONObject object = JSONObject.fromObject(result);
        String access_token = object.getString("access_token");  //一旦code过期或旧code,这里将无法获取access_token
        //获取openid
        String openid = object.getString("openid");
        //带着openid和access_token去获取用户资源信息
        String user_result_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +access_token+
                "&openid=" +openid+
                "&lang=zh_CN";
        //获取到了用户资源
        JSONObject user_reuslt = JSONObject.fromObject(EntityUtils.toString(new DefaultHttpClient().execute(new HttpPost(user_result_url)).getEntity(), "UTF-8"));
         String openid1 = user_reuslt.getString("openid");
         String nickname = user_reuslt.getString("nickname");//昵称
         String sex = user_reuslt.getString("sex");//性别
         String language = user_reuslt.getString("language");//语言
         String city = user_reuslt.getString("city");//地址
         String province = user_reuslt.getString("province");//省份
         String country = user_reuslt.getString("country");//国籍
         String headimgurl = user_reuslt.getString("headimgurl");//头像链接

         return user_reuslt.toString(); //输出

    }

}





